#!/usr/bin/env node
/*
 * @Date: 2021-12-06 11:00:47
 * @Version: 1.0.0
 * @Author: chenhengling
 * @Description: init命令
 * @FilePath: \template-cli\src\cmds\init.js
 * @LastEditTime: 2021-12-06 15:31:39
 * @LastEditors: chenhengling
 */
const { program } = require('commander');
const path = require('path');
const fs = require('fs');
const ora = require('ora');
const { prompt } = require('../utils/prompt');
const downloadRepo = require('../utils/download');
const updateRepo = require('../utils/update');
const { log } = require('../utils');
const { templates } = require('../utils/config');

program
  .description('generate a project from a remote template')
  .helpOption('-h, --help', 'Output usage information')
  .action(initAction);

async function initAction() {
  const answers = await prompt();
  const localPath = path.resolve(process.cwd(), answers.name);
  const template = templates.find((v) => v.type === answers.type);

  if (!template || !template.url) {
    log('未找到该类型模板');
    return;
  }

  if (fs.existsSync(localPath)) {
    log(`当前目录下已存在同名目录 - ${answers.name}`);
    return;
  }

  const spinner = ora('正在初始化项目模板...').start();

  try {
    // 下载库文件
    await downloadRepo(template, localPath);

    // 更新库文件
    await updateRepo(
      localPath,
      { name: answers.name, description: answers.description, author: answers.author },
      template.deleteFiles
    );

    spinner.succeed();
    log('项目模板初始化完成', true);
  } catch (err) {
    spinner.fail();
    log(err);
  } finally {
    process.exit(1);
  }
}

program.parseAsync(process.argv);
